package ssm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import ssm.pojo.Admin;
import ssm.pojo.Result;
import ssm.service.IAdminService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author: lzp
 * @Date: 2020/9/30 11:31
 * @Description:
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    IAdminService adminService;
    @Autowired
    HttpSession session;

    /**
     * 登录
     * @param loginAdmin
     * @param checkCode
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result login(Admin loginAdmin, String checkCode,HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        String CHECKNUM = (String) session.getAttribute("CHECKNUM");
        if (!CHECKNUM.equals(checkCode)) {
            result.setFlag(false);
            result.setMsg("验证码错误！！");
            return result;
        }
        Admin admin = adminService.login(loginAdmin);
        if (admin != null) {
            if (admin.getPassword().equals(loginAdmin.getPassword())) {
                Cookie cookie = new Cookie("JSESSIONID", session.getId());
                cookie.setMaxAge(24 * 60 * 60);
                response.addCookie(cookie);
                session.setAttribute("admin", admin);
                result.setFlag(true);
                result.setMsg("亲爱的 " + admin.getName() + " 欢迎回来！！");
                return result;
            }
        }
        result.setFlag(false);
        result.setMsg("账号或密码错误！！");
        return result;
    }

    /**
     * 修改密码
     * @param password
     * @return
     */
    @RequestMapping("/changePwd")
    @ResponseBody
    public Result changePwd(String password) {
        Admin admin = (Admin) session.getAttribute("admin");
        Result result = new Result();
        admin.setPassword(password);
        boolean flag = adminService.changePwd(admin);
        result.setFlag(flag);
        if (flag) {
            session.removeAttribute("admin");
            session.invalidate();
            result.setMsg("密码修改成功！！请重新登录");
        } else {
            result.setMsg("密码修改失败！！请检测输入格式！");
        }
        return result;
    }

    /**
     * 注销
     * @return
     */
    @RequestMapping("/logout")
    public String logout() {
        if (session != null) {
            session.removeAttribute("admin");
        }
        return "redirect:/app/login";
    }

}
